package com.fancon.android.rpc;

import java.io.IOException;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.fancon.android.xchannel.entity.Photo;

public class XChannelApiService extends FanconApiService{
	public static final String ROOT_API = "http://vngirlx.appspot.com/";
	public XChannelApiService(Context context, String apiRoot) {
		super(context, apiRoot);
		// TODO Auto-generated constructor stub
	}
	public XChannelApiService(Context context){
		super(context, ROOT_API);
	}
	
	public ArrayList<Photo> getPhotos(int index) throws JSONException,
			IOException, org.json.JSONException, NoSuchAlgorithmException {
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		paramList.add(new BasicNameValuePair("action", "numpage"));
		paramList.add(new BasicNameValuePair("index", String.valueOf(index)));
		ApiConnect api = new ApiConnect(mContext);
		String subUrl = "channel19json";
		//String result = api.getApiDataWithCachePriority(ROOT_API + subUrl, paramList);
		String result = api.getApiData(ROOT_API + subUrl, paramList);
		ArrayList<Photo> photos = new ArrayList<Photo>();
		JSONArray jobjects = new JSONArray(result);
		JSONObject phoJson = null;
		for (int i = 0; i < jobjects.length(); i++) {
			phoJson = jobjects.getJSONObject(i);
			Photo photo = new Photo();
			if (phoJson.opt("id") != null) {
				photo.setId(phoJson.getLong("id"));
			}
			if (phoJson.opt("title") != null) {
				photo.setTitle(URLDecoder.decode(phoJson.getString("title"),
						"UTF-8"));
			}
			if (phoJson.opt("thumbUrl") != null) {
				photo.setThumbUrl(phoJson.getString("thumbUrl"));
			}
			if (phoJson.opt("imageUrl") != null) {
				photo.setImageUrl(phoJson.getString("imageUrl"));
			}
			if (phoJson.opt("date") != null) {
				photo.setDate(new Date(phoJson.getLong("date")));
			}
			photos.add(photo);
		}
		return photos;
	}
}
